import { useState, useOptimistic, useTransition } from "react";
function reducer(state, action) {
  switch (action.type) {
    case "increment":
      return state + 1;
    case "decrement":
      return state - 1;
    default:
      return state;
  }
}
function Counter() {
  // 1. 声明计数的状态
  const [count, setCount] = useState(0);

  //实现乐观更新
  // 2. optimisticState 是乐观状态
  // addOptimisticState 像以前dispatch,用来派发动作
  // reducer 和以前的 reduer 一样
  const [optimisticState, addOptimisticState] = useOptimistic(count, reducer);
  // 3. 1 使用 useTransition
  const [isPending, startTransition] = useTransition();
  const handleIncrement = async () => {
    // 3. 2 必须把 addOptimisticState 操作放在 startTransition 的里面
    // 因为要通过startTransition实现失败回滚的操作
    startTransition(async () => {
      // 3.3 派发乐观状态 修改状态
      addOptimisticState({ type: "increment" });
      try {
        // 3.4 等待 真实状态
        await new Promise((resolve, reject) => setTimeout(reject, 2000)).then(
          () => {
            //  3.5 一旦修改了count值，那么会立刻让optimisticState和count保持一致，真正改，就是这里，不然会回滚以前值
            setCount((count) => count + 1);
          }
        );
        console.log("next");
      } catch (error) {
        console.log(error);
      }
    });
  };
  return (
    <div>
      <p>count:{optimisticState}</p>
      <button onClick={handleIncrement} disabled={isPending}>
        {isPending ? "...." : "+"}
      </button>
    </div>
  );
}
export default Counter;
/**
An optimistic state update occurred outside a transition or action.
 To fix, move the update to an action, or wrap with startTransition.
 适合
 1. 成功率非常非常高
 2. UI的变化特别简单
 */
